﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

namespace AyuBookmark.WinForm.Controls
{
    /// <summary>
    /// 增强型搜索框控件（支持自动补全、历史记录和筛选器）
    /// </summary>
    public class SearchBox : UserControl
    {
        private TextBox txtSearch;
        private Button btnClear;
        private Button btnDropdown;
        private ContextMenuStrip dropdownMenu;
        private System.Windows.Forms.Timer searchTimer; // 明确指定Timer类型
        private List<string> searchHistory = new List<string>();
        private const int HistoryMaxCount = 10;

        // 公共事件
        public event EventHandler<string> SearchTriggered;
        public event EventHandler<string> QuickFilterChanged;

        public SearchBox()
        {
            InitializeComponents();
            SetupEvents();
        }

        private void InitializeComponents()
        {
            // 基础设置
            this.SuspendLayout();
            this.BackColor = Color.White;
            this.BorderStyle = BorderStyle.FixedSingle;
            this.Size = new Size(300, 30);

            // 搜索文本框
            this.txtSearch = new TextBox();
            this.txtSearch.BorderStyle = BorderStyle.None;
            this.txtSearch.Dock = DockStyle.Fill;
            this.txtSearch.Font = new Font("Microsoft YaHei", 10f);
            this.txtSearch.Margin = new Padding(5, 0, 30, 0);

            // 清除按钮
            this.btnClear = new Button();
            this.btnClear.FlatStyle = FlatStyle.Flat;
            this.btnClear.FlatAppearance.BorderSize = 0;
            this.btnClear.BackColor = Color.Transparent;
            this.btnClear.Text = "X"; // 使用文本代替图标
            this.btnClear.Font = new Font("Microsoft YaHei", 9f, FontStyle.Bold);
            this.btnClear.ForeColor = Color.Gray;
            this.btnClear.Size = new Size(25, 25);
            this.btnClear.Location = new Point(this.Width - 55, 2);
            this.btnClear.Anchor = AnchorStyles.Top | AnchorStyles.Right;
            this.btnClear.Visible = false;

            // 下拉按钮
            this.btnDropdown = new Button();
            this.btnDropdown.FlatStyle = FlatStyle.Flat;
            this.btnDropdown.FlatAppearance.BorderSize = 0;
            this.btnDropdown.BackColor = Color.Transparent;
            this.btnDropdown.Text = "▼"; // 使用文本代替图标
            this.btnDropdown.Font = new Font("Microsoft YaHei", 8f);
            this.btnDropdown.Size = new Size(25, 25);
            this.btnDropdown.Location = new Point(this.Width - 30, 2);
            this.btnDropdown.Anchor = AnchorStyles.Top | AnchorStyles.Right;

            // 下拉菜单
            this.dropdownMenu = new ContextMenuStrip();
            this.dropdownMenu.Items.Add("搜索历史").Font = new Font("Microsoft YaHei", 9f, FontStyle.Bold);
            this.dropdownMenu.Items.Add("-"); // 分隔线
            this.dropdownMenu.Items.Add("按标题筛选").Click += (s, e) => SetQuickFilter("title:");
            this.dropdownMenu.Items.Add("按URL筛选").Click += (s, e) => SetQuickFilter("url:");
            this.dropdownMenu.Items.Add("按标签筛选").Click += (s, e) => SetQuickFilter("tag:");

            // 搜索延迟计时器
            this.searchTimer = new System.Windows.Forms.Timer();
            this.searchTimer.Interval = 500;
            this.searchTimer.Tick += (s, e) => TriggerSearch();

            // 添加控件
            this.Controls.Add(this.txtSearch);
            this.Controls.Add(this.btnClear);
            this.Controls.Add(this.btnDropdown);

            // 设置占位文本（使用SendMessage API）
            SetPlaceholderText(txtSearch, "输入搜索内容...");

            this.ResumeLayout(false);
        }

        private void SetupEvents()
        {
            // 文本框事件
            this.txtSearch.TextChanged += (s, e) =>
            {
                btnClear.Visible = !string.IsNullOrEmpty(txtSearch.Text);
                searchTimer.Stop();
                searchTimer.Start();
            };

            this.txtSearch.KeyDown += (s, e) =>
            {
                if (e.KeyCode == Keys.Enter) TriggerSearch();
            };

            // 按钮事件
            this.btnClear.Click += (s, e) =>
            {
                txtSearch.Clear();
                btnClear.Visible = false;
                TriggerSearch();
            };

            this.btnDropdown.Click += (s, e) =>
            {
                UpdateHistoryMenu();
                dropdownMenu.Show(btnDropdown, new Point(0, btnDropdown.Height));
            };
        }

        #region 公共方法
        /// <summary>
        /// 设置搜索框提示文本
        /// </summary>
        public string Placeholder
        {
            set => SetPlaceholderText(txtSearch, value);
        }

        /// <summary>
        /// 获取或设置搜索文本
        /// </summary>
        public string SearchText
        {
            get => txtSearch.Text;
            set => txtSearch.Text = value;
        }

        /// <summary>
        /// 添加搜索历史记录
        /// </summary>
        public void AddHistory(string keyword)
        {
            if (string.IsNullOrWhiteSpace(keyword)) return;

            searchHistory.RemoveAll(x => x.Equals(keyword, StringComparison.OrdinalIgnoreCase));
            searchHistory.Insert(0, keyword);

            if (searchHistory.Count > HistoryMaxCount)
                searchHistory.RemoveRange(HistoryMaxCount, searchHistory.Count - HistoryMaxCount);
        }

        /// <summary>
        /// 清空搜索历史
        /// </summary>
        public void ClearHistory()
        {
            searchHistory.Clear();
        }
        #endregion

        #region 私有方法
        private void TriggerSearch()
        {
            searchTimer.Stop();
            if (!string.IsNullOrEmpty(txtSearch.Text))
                AddHistory(txtSearch.Text);
            SearchTriggered?.Invoke(this, txtSearch.Text);
        }

        private void SetQuickFilter(string filter)
        {
            txtSearch.Text = filter;
            txtSearch.Focus();
            txtSearch.SelectionStart = txtSearch.Text.Length;
            TriggerSearch();
        }

        private void UpdateHistoryMenu()
        {
            // 清除旧的历史菜单项（保留前两个固定项）
            while (dropdownMenu.Items.Count > 3)
                dropdownMenu.Items.RemoveAt(3);

            // 添加历史记录
            foreach (var history in searchHistory)
            {
                var item = new ToolStripMenuItem(history);
                item.Click += (s, e) =>
                {
                    txtSearch.Text = history;
                    TriggerSearch();
                };
                dropdownMenu.Items.Add(item);
            }
        }

        // 使用Win32 API设置占位文本
        private void SetPlaceholderText(TextBox textBox, string placeholder)
        {
            const int EM_SETCUEBANNER = 0x1501;
            NativeMethods.SendMessage(textBox.Handle, EM_SETCUEBANNER, 0, placeholder);
        }
        #endregion

        protected override void OnResize(EventArgs e)
        {
            base.OnResize(e);
            btnClear.Location = new Point(this.Width - 55, 2);
            btnDropdown.Location = new Point(this.Width - 30, 2);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                searchTimer?.Dispose();
                dropdownMenu?.Dispose();
            }
            base.Dispose(disposing);
        }
    }

    internal static class NativeMethods
    {
        [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
        public static extern int SendMessage(IntPtr hWnd, int msg, int wParam, string lParam);
    }
}